import 'package:flutter/material.dart';
import 'package:like_chat/blocs/message_list_bloc.dart';
import 'package:like_chat/entity/Messages.dart';
import 'package:like_chat/entity/user.dart';
import 'package:like_chat/widget/message_list_widget.dart';
import 'package:web_socket_channel/io.dart';

String globalFriendId = null;

class ChatPage extends StatefulWidget {
  final String friendName;

  final String friendId;

  final User user;

  final IOWebSocketChannel webSocketChannel;

  ChatPage({this.friendName, this.friendId, this.user, this.webSocketChannel}) {
    globalFriendId = friendId;
  }

  @override
  _ChatPageState createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  MessageListBloc _messageListBloc;

  TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
    _messageListBloc = MessageListBloc(widget.webSocketChannel);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.friendName),
        centerTitle: true,
      ),
      body: Column(
        children: <Widget>[
          MessageListWidget(_messageListBloc, widget.user),
          _inputMessageWidget(),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _messageListBloc.dispose();
    super.dispose();
  }

  _inputMessageWidget() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Expanded(
            child: TextField(
              controller: _controller,
            ),
          ),
          IconButton(
              icon: Icon(Icons.send),
              onPressed: () => _onSubmit(_controller.text))
        ],
      ),
    );
  }

  void _onSubmit(String value) {
    final msg = Messages(
        mid: "1111",
        type: 0,
        status: 0,
        content: value,
        toId: "tiantian",
        fromId: "peng");
    _messageListBloc.addMessage(msg);
    _controller.clear();
  }
}
